package com.thirtydays.frame.ui.text

import android.content.Context
import android.text.InputFilter
import android.text.InputType
import android.text.method.DigitsKeyListener
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.thirtydays.frame.R
import com.thirtydays.frame.databinding.PerfectTextViewBinding
import com.thirtydays.frame.util.ext.gone
import com.thirtydays.frame.util.ext.visible


/**
 * @author 小垚
 * @创建时间： 2021/4/21
 * @描述：自定义左右TextView,edittext
 **/

class PerfectTextView : FrameLayout {

    lateinit var viewBinding: PerfectTextViewBinding

    constructor(context: Context) : this(context, null) {}

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(context, attrs, defStyleAttr)
    }

    private fun initView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        viewBinding = PerfectTextViewBinding.inflate(LayoutInflater.from(context), this, true)

        val attrs = context.obtainStyledAttributes(attrs, R.styleable.PerfectTextView)

        val isMore = attrs.getBoolean(R.styleable.PerfectTextView_isMore, true)

        val keyName = attrs.getString(R.styleable.PerfectTextView_keyName)

        val valueName = attrs.getString(R.styleable.PerfectTextView_valueName)

        val isTv = attrs.getBoolean(R.styleable.PerfectTextView_isTv, true)

        val etHint = attrs.getString(R.styleable.PerfectTextView_etHint)

        val maxLenght = attrs.getInt(R.styleable.PerfectTextView_ptv_lenght, Int.MAX_VALUE)

        val intype = attrs.getInt(R.styleable.PerfectTextView_ptv_type, InputType.TYPE_CLASS_TEXT)

        val digits = attrs.getString(R.styleable.PerfectTextView_ptv_digits)

        viewBinding.etValue.filters = arrayOf(InputFilter.LengthFilter(maxLenght))
        viewBinding.etValue.inputType = intype

        if (digits != null && digits.isNotEmpty()) {
            viewBinding.etValue.keyListener = DigitsKeyListener.getInstance(digits);
        }



        viewBinding.tvKey.text = keyName

        if (isMore) {
            viewBinding.ivMore.visible()
        } else {
            viewBinding.ivMore.gone()
        }

        if (isTv) {
            viewBinding.tvValue.visible()
            viewBinding.etValue.gone()
            viewBinding.tvValue.text = valueName
            viewBinding.tvValue.hint = etHint
        } else {
            viewBinding.etValue.visible()
            viewBinding.tvValue.gone()
            viewBinding.etValue.setText(valueName)
            viewBinding.etValue.hint = etHint
        }
    }
}